<template>
  <div class="example1-wrapper" >
    <div class="fr clearfix mb15">
      <bk-form form-type="inline">
        <bk-form-item label="业务">
          <bk-select
              :disabled="false"
              style="width: 250px;"
              ext-cls="select-custom"
              @change="handleBizChange"
              ext-popover-cls="select-popover-custom"
              searchable>
            <bk-option
                v-for="item in biz_list"
                :key="item.bk_biz_id"
                :id="item.bk_biz_id"
                :name="item.bk_biz_id+'-'+item.bk_biz_name"></bk-option>
          </bk-select>
        </bk-form-item>
        <bk-form-item label="集群">
          <bk-select
              v-model="set_id"
              :disabled="false"
              style="width: 250px;"
              ext-cls="select-custom"
              @change="handleSetChange"
              ext-popover-cls="select-popover-custom"
              searchable>
            <bk-option
                v-for="item in set_list"
                :key="item.bk_set_id || ''"
                :id="item.bk_set_id || ''"
                :name="`${item.bk_set_id || '未知'}-${item.bk_set_name || '未命名'}`"></bk-option>
          </bk-select>
        </bk-form-item>
        <bk-form-item label="模块">
          <bk-select
              v-model="module_id"
              :disabled="false"
              style="width: 250px;"
              ext-cls="select-custom"
              @change="handleModuleChange"
              ext-popover-cls="select-popover-custom"
              searchable>
            <bk-option
                v-for="item in module_list"
                :key="item.bk_module_id || ''"
                :id="item.bk_module_id || ''"
                :name="`${item.bk_module_id || '未知'}-${item.bk_module_name || '未命名'}`">
            </bk-option>
          </bk-select>
        </bk-form-item>
        <bk-form-item label="操作人">
          <bk-input placeholder="操作人" @change="handleOperatorChange" v-model="operator" />
        </bk-form-item>
        <bk-form-item>
          <bk-button theme="primary" title="查询" @click="searchHosts">查询</bk-button>
        </bk-form-item>
      </bk-form>
    </div>

    <bk-table style="margin-top: 15px;"
              :data="host_list"
              :size="size"
              :pagination="pagination"
              @page-change="handlePageChange">
      <bk-table-column label="主机ID" prop="bk_host_id" />
      <bk-table-column label="主机IP" prop="bk_host_innerip" />
      <bk-table-column label="操作人" prop="operator" />
      <bk-table-column label="备份维护人" prop="bk_bak_operator" />
      <bk-table-column label="操作" width="150">
        <template slot-scope="props">
          <bk-button theme="primary"
                     text :disabled="props.row.status === '创建中'" @click="getHostDetail(props.row)">查看详情</bk-button>
        </template>
      </bk-table-column>
    </bk-table>


    <bk-sideslider
        class="bk-layout-component-nelgpjna sideslider1e5ab"
        :is-show.sync="isSidesliderShow"
        :title="('主机详情')"
        :show-mask="false"
        :width="600"
        direction="right">
      <template slot="content">
        <div class="step-detail-container">
          <div class="step-detail-item" v-for="item in host_detail" :key="item.bk_property_id">
            <strong>{{ item.bk_property_name + '：' }}</strong>
            <span>{{ item.bk_property_value ? item.bk_property_value : '无' }}</span>
          </div>
        </div>
      </template>
    </bk-sideslider>
  </div>


</template>

<script>
export default {
  components: {
  },
  data() {
    return {
      size: 'small',
      formData: {
        name: '',
        date: '',
      },
      isSearching: false,
      tableData: [],
      biz_list:  [],  // 业务列表
      set_list:  [],  // 集群列表
      module_list: [],  // 模块列表
      host_list:  [], //主机列表
      host_detail:[], //主机详情列表
      biz_id:null,    // 当前选中的业务ID
      set_id:null,    // 当前选中的集群ID
      module_id:null, // 当权选中的模块ID
      operator:null,  // 操作人
      bak_operator:null,  // 备份维护人
      isSidesliderShow: false,  // 控制侧边栏的显示
      pagination: {
        current: 1,
        count: 0,
        limit: 10,
      },
    };
  },
  created() {
    this.init();  // 通过created()钩子函数，执行初始化操作
  },
  methods: {
    init() {
      this.getBizData();  // 页面初始化时执行
    },
    async getBizData() {
      try {
        console.log('当前环境:', process.env.BK_PAAS_ENVIRONMENT)
        const res = await this.$store.dispatch('example/getBizData', {
          params: {},           // 原来的第二个参数 {}
          config: { fromCache: true }  // 原来的第三个参数 {fromCache: true}
        }); // 传一个对象，包含 params 和 config
        this.biz_list = res.data.info;
        if (this.biz_list.length > 0) {
          this.biz_id = this.biz_list[0].bk_biz_id; // 假设字段是 bk_biz_id
          console.log(this.biz_id);
          console.log("不存在");
        }
      } catch (e) {
        console.error(e);
      }
    },
    async handleBizChange(newValue, oldValue) {
      // ...
      console.log("存在"+newValue);
      const set_res = await this.$store.dispatch('example/getSetData', {
           bk_biz_id: newValue,
        params: { "bk_biz_id": newValue },     // 原来的 {"bk_biz_id":newValue}
        config: { fromCache: true }            // 原来的 {fromCache:true}
      }); // 传一个对象
      this.set_list = set_res.data.info;
    },
    async handleSetChange(newValue, oldValue) {
      // ...
      const module_res = await this.$store.dispatch('example/getModuleData', {
          bk_biz_id: this.biz_id,
          bk_set_id: this.set_id,
        config: { fromCache: true } // 原来的 {fromCache:true}
      }); // 传一个对象
      this.module_list = module_res.data.info;
    },
    async handleModuleChange(newValue, oldValue) {
      // 点击集群ID后，查询集群下所有模块，并回显至对应组件
      console.log('切换了模块，模块ID为：',newValue)
      this.module_id = newValue
    },
    async handleOperatorChange(value,event){
      try{
        console.log('维护人输入框，当前输入值为',value)
        this.operator = value
      }catch (e) {
        console.error(e)
      }
    },
    async searchHosts() {
      // --- 1. 参数校验 ---
      if (!this.biz_id) {
        this.$bkMessage({
          theme: 'warning',
          message: '请先选择一个业务'
        });
        return;
      }

      // --- 2. 构建查询参数 ---
      const query_data = {
        bk_biz_id: this.biz_id
      };

      // 可选参数：集群、模块、操作人
      if (this.set_id) {
        query_data.bk_set_id = this.set_id;
      }
      if (this.module_id) {
        query_data.bk_module_id = this.module_id;
      }
      if (this.operator) {
        query_data.operator = this.operator;
      }

      //  新增：支持主机ID、主机IP查询
      if (this.host_id) {
        query_data.bk_host_id = this.host_id;
      }
      if (this.host_ip) {
        query_data.bk_host_innerip = this.host_ip; // 或 bk_host_outerip
      }

      console.log('主机查询参数:', query_data);

      // --- 3. 重置分页 ---
      this.pagination.current = 1;

      // --- 4. 添加加载状态 ---
      this.$set(this, 'isSearching', true); // 响应式变量

      try {
        const host_res = await this.$store.dispatch('example/getHostsData', {
          params: query_data,
          config: { fromCache: true }
        });

        // --- 5. 安全校验并赋值 ---
        if (host_res && host_res.data && Array.isArray(host_res.data.info)) {
          this.host_list = host_res.data.info;
          this.pagination.count = host_res.data.info.length; // 或从接口返回总条数
          console.log("长度"+this.pagination.count);
        } else {
          this.host_list = [];
          this.pagination.count = 0;
          console.warn('主机数据格式异常:', host_res);
          this.$bkMessage({
            theme: 'warning',
            message: '未获取到主机数据'
          });
        }
      } catch (error) {
        console.error('查询主机失败:', error);
        this.$bkMessage({
          theme: 'error',
          message: '查询主机失败，请稍后重试'
        });
        this.host_list = [];
        this.pagination.count = 0;
      } finally {
        this.$set(this, 'isSearching', false); // 关闭加载
      }
    },
    handlePageChange(page) {  // 页码变化检测
      this.pagination.current = page;
    },
    remove(row) {
      const index = this.tableData.indexOf(row);
      if (index !== -1) {
        this.tableData.splice(index, 1);
      }
    },
    async getHostDetail(host) {
      if (!host || !host.bk_host_id) {
        this.$bkMessage({
          theme: 'warning',
          message: '主机信息不完整，无法查看详情'
        });
        return;
      }
      console.log("日志测试");
      try {
        const res = await this.$store.dispatch('example/getHostDetail', {
            bk_host_id: host.bk_host_id,
            bk_biz_id: host.bk_biz_id,
          config: { fromCache: true }
        });
        if (res && res.data) {
          // 假设 res.data.info 是主机属性列表
          this.host_detail = res.data; // 更新侧边栏数据
          this.isSidesliderShow = true;     // 显示侧边栏
        }
      } catch (err) {
        console.error('获取主机详情失败:', err);
        this.$bkMessage({
          theme: 'error',
          message: '获取详情失败'
        });
      }
    }
  }
};
</script>
